package com.erp.common.web;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.erp.app.admin.userSetup.pk.UserPk;
import com.erp.app.admin.userSetup.vo.UserVo;
import com.erp.app.common.ProjectConstants;
import com.erp.framework.controller.action.SimpleUserStyleAction;
import com.erp.framework.model.dao.ServiceLocator;
import com.erp.framework.model.delegate.SimpleSearchMaintStyleDelegate;
import com.erp.framework.util.logger.Logger;

public class ChangePasswordAction extends SimpleUserStyleAction {

    private final String actionUpdatePassword = "updatePassword";

    protected String getMasterFormSessionName() {
        return "changePasswordForm";
    }

    protected String getModuleName(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response){
        return "";
    }
    
    protected ActionForward otherExecute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response) throws ServletException {
        HttpSession session = request.getSession(false);
        
        ChangePasswordForm form = (ChangePasswordForm) formIn;
        String action = form.getPageEvent();
        action = (action == null) ? "" : action.trim();
        ActionForward actionForward = new ActionForward(mapping.getInput());
        ActionErrors errors = new ActionErrors();

        try {
            if (!isHandled(request) && action.equalsIgnoreCase(actionUpdatePassword)) {
                setHandled(request);
                actionForward = processActionUpdatePassword(mapping, formIn, request, response, errors);
                saveToken(request);
            }

        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        }

        saveErrors(request, errors);
        return actionForward;
    }
    
    protected ActionForward processActionUpdatePassword(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        ChangePasswordForm form = (ChangePasswordForm) formIn;
        HttpSession session = request.getSession(false);
        ActionForward actionForward = new ActionForward(mapping.getInput());
        form.otherValidate(errors);
        if (errors.size() != 0)
            return actionForward;
        
        try {
	        SimpleSearchMaintStyleDelegate dg = new SimpleSearchMaintStyleDelegate();
	        UserVo vo = (UserVo) dg.findByPrimaryKey(new UserVo(), new UserPk(form.getUserCode(), form.getCompanyCode()));
	        if (vo != null) {
	        	vo.setPassword(form.getNewPasswd());
	        	dg.updateMaster(vo);
	        	session.setAttribute(ProjectConstants.SESSION_ALERT_AFTER_UPDATE_PASSWORD, ProjectConstants.GENERIC_YES);
	        }
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        	errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.general", e.getMessage()));
        }
        return actionForward;
    }
    
// Old way: will cause JNDI naming exception in WebSphere server    
/*
    protected ActionForward processActionUpdatePassword(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        ChangePasswordForm form = (ChangePasswordForm) formIn;
        HttpSession session = request.getSession(false);
        ActionForward actionForward = new ActionForward(mapping.getInput());
        form.otherValidate(errors);
        if (errors.size() != 0)
            return actionForward;
        Connection conn = null;
        PreparedStatement pStmt = null;

        int count = 0;

        ServiceLocator srvLocator = ServiceLocator.getInstance();
        UserTransaction userTrans = srvLocator.getUserTransaction();
        try {
            userTrans.begin();
            try {
                conn = ServiceLocator.getInstance().getDSDBConnection();
                pStmt = conn.prepareStatement(sqlUpdate());
                setValuesForUpdate(pStmt, form);
                count = pStmt.executeUpdate();

                if (count != 1) {
                    errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.login.password.oldPassword"));
                    return actionForward;
                    // throw new Exception("ChangePasswordAction,
                    // processActionUpdatePassword old password not match");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            userTrans.commit();
            session.setAttribute(ProjectConstants.SESSION_ALERT_AFTER_UPDATE_PASSWORD, ProjectConstants.GENERIC_YES);

        } catch (Exception e) {
            System.out.println("error in ChangePasswordAction: " + e);
            try {
                userTrans.rollback();
            } catch (Exception e1) {

            }
        } finally {
            try {
                if (pStmt != null)
                    pStmt.close();
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return actionForward;
    }

    protected String sqlUpdate() {
        return " UPDATE T_USER SET PASSWORD=?, UPDATE_USER=? ,UPDATE_DATE=sysdate" + " WHERE COMPANY_CODE=? "
                + " AND USER_CODE=? " + " AND PASSWORD=? ";
    }

    protected void setValuesForUpdate(PreparedStatement pStmt, Object obj) throws SQLException {
        ChangePasswordForm form = (ChangePasswordForm) obj;
        int i = 1;
        pStmt.setString(i++, form.getNewPasswd().toUpperCase());
        pStmt.setString(i++, form.getUserCode());
        pStmt.setString(i++, form.getCompanyCode());
        pStmt.setString(i++, form.getUserCode());
        pStmt.setString(i++, form.getOldPasswd());
    }
*/
}
